<template>
    <div class="position-management-container">
        <pageTitle :title="'職位管理'" />
        <!-- 頂部搜索和按鈕區域 -->
        <div class="top-action-bar">
            <el-row :gutter="20" align="middle">
                <el-col :span="12">
                    <el-input placeholder="請輸入職位名稱或編碼" v-model="searchQuery" class="search-input-with-button" clearable
                        @clear="handleSearch" @keyup.enter="handleSearch">
                        <template #append>
                            <el-button type="primary" @click="handleSearch">
                                <el-icon>
                                    <search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="12" class="action-buttons">
                    <el-button type="primary" @click="showAddDialog">
                        <el-icon>
                            <plus />
                        </el-icon>
                        <span>新增職位</span>
                    </el-button>
                    <el-button type="success" @click="importData">
                        <el-icon>
                            <upload />
                        </el-icon>
                        <span>導入</span>
                    </el-button>
                    <el-dropdown>
                        <el-button type="info">
                            <span>更多操作</span>
                            <el-icon class="el-icon--right">
                                <arrow-down />
                            </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="exportData">導出數據</el-dropdown-item>
                                <el-dropdown-item @click="batchEnable">批量啟用</el-dropdown-item>
                                <el-dropdown-item @click="batchDisable">批量禁用</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-col>
            </el-row>
        </div>

        <!-- 主體內容區域 -->
        <div class="main-content-wrapper">
            <el-row :gutter="20">
                <!-- 左側職位類別樹 -->
                <el-col :span="5">
                    <div class="position-category-card">
                        <div class="tree-header">
                            <span class="tree-title">職位類別</span>
                            <el-button type="text" @click="refreshTree">
                                <el-icon>
                                    <refresh />
                                </el-icon>
                                <span>刷新</span>
                            </el-button>
                        </div>
                        <el-tree :data="categoryTree" :props="treeProps" node-key="id" default-expand-all
                            highlight-current :expand-on-click-node="false" @node-click="handleNodeClick">
                            <template #default="{ node, data }">
                                <span class="custom-tree-node">
                                    <span>{{ node.label }}</span>
                                    <span v-if="data.count" class="node-count">({{ data.count }})</span>
                                </span>
                            </template>
                        </el-tree>
                    </div>
                </el-col>

                <!-- 右側職位表格 -->
                <el-col :span="19">
                    <div class="position-table-card">
                        <el-table :data="positionList" style="width: 100%" v-loading="loading" class="no-border-table">
                            <el-table-column prop="code" label="職位編碼" width="120" align="center" />
                            <el-table-column prop="name" label="職位名稱" width="150" align="center" />
                            <el-table-column prop="department" label="所在部門" align="center" />
                            <el-table-column prop="jobTitle" label="對應職務" width="150" align="center" />
                            <el-table-column prop="jobLevel" label="職務級別" width="120" align="center" />
                            <el-table-column label="職位狀態" width="100" align="center">
                                <template #default="{ row }">
                                    <el-tag :type="row.status === 'enabled' ? 'success' : 'danger'" size="small">
                                        {{ row.status === 'enabled' ? '啟用' : '禁用' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="180" align="center" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" size="small" @click="editPosition(row)">
                                        編輯
                                    </el-button>
                                    <el-button type="danger" size="small" @click="deletePosition(row)">
                                        刪除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="pagination-wrapper">
                            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                                :page-sizes="[10, 20, 50, 100]" :small="true" :background="true"
                                layout="total, sizes, prev, pager, next, jumper" :total="total"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <!-- 新增/編輯職位對話框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '編輯職位' : '新增職位'" width="600px">
            <el-form :model="positionForm" :rules="rules" ref="positionFormRef" label-width="100px">
                <el-form-item label="職位名稱" prop="name">
                    <el-input v-model="positionForm.name" placeholder="請輸入職位名稱" />
                </el-form-item>
                <el-form-item label="職位編碼" prop="code">
                    <el-input v-model="positionForm.code" placeholder="請輸入職位編碼" />
                </el-form-item>
                <el-form-item label="所屬組織" prop="organization">
                    <el-select v-model="positionForm.organization" placeholder="請選擇所屬組織" style="width: 100%">
                        <el-option v-for="org in organizations" :key="org.id" :label="org.name" :value="org.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="職位類別" prop="category">
                    <el-select v-model="positionForm.category" placeholder="請選擇職位類別" style="width: 100%">
                        <el-option-group v-for="group in categories" :key="group.id" :label="group.name">
                            <el-option v-for="item in group.children" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="對應職務" prop="jobTitle">
                    <el-select v-model="positionForm.jobTitle" placeholder="請選擇對應職務" style="width: 100%">
                        <el-option v-for="job in jobTitles" :key="job.id" :label="job.name" :value="job.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="職務級別" prop="jobLevel">
                    <el-select v-model="positionForm.jobLevel" placeholder="請選擇職務級別" style="width: 100%">
                        <el-option v-for="level in jobLevels" :key="level.id" :label="level.name" :value="level.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="職位描述" prop="description">
                    <el-input v-model="positionForm.description" type="textarea" :rows="3" placeholder="請輸入職位描述" />
                </el-form-item>
                <el-form-item label="職位狀態" prop="status">
                    <el-switch v-model="positionForm.status" active-value="enabled" inactive-value="disabled"
                        active-text="啟用" inactive-text="禁用" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">確定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus, Upload, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import pageTitle from "@/components/pageTitle/pageTitle.vue"

// 響應式數據
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const positionFormRef = ref(null)

// 職位類別樹數據
const categoryTree = ref([
    {
        id: 1,
        label: '默認分類1',
        count: 5,
        children: [
            { id: 3, label: '行政類', count: 2 },
            { id: 4, label: '技術類', count: 3 }
        ]
    },
    {
        id: 2,
        label: '默認分類2',
        count: 4,
        children: [
            { id: 5, label: '管理類', count: 2 },
            { id: 6, label: '銷售類', count: 2 }
        ]
    }
])

const treeProps = {
    children: 'children',
    label: 'label'
}

// 職位列表數據
const positionList = ref([
    {
        id: 1,
        code: 'POS001',
        name: '行政專員',
        department: '行政部',
        jobTitle: '行政專員',
        jobLevel: 'P1',
        status: 'enabled',
        description: '負責日常行政事務'
    },
    {
        id: 2,
        code: 'POS002',
        name: '前端工程師',
        department: '技術部',
        jobTitle: '工程師',
        jobLevel: 'P2',
        status: 'enabled',
        description: '負責前端開發工作'
    },
    {
        id: 3,
        code: 'POS003',
        name: '銷售經理',
        department: '銷售部',
        jobTitle: '經理',
        jobLevel: 'M2',
        status: 'enabled',
        description: '負責銷售團隊管理'
    },
    {
        id: 4,
        code: 'POS004',
        name: '人事專員',
        department: '人事部',
        jobTitle: '人事專員',
        jobLevel: 'P1',
        status: 'disabled',
        description: '負責招聘和員工關係'
    }
])

// 表單數據
const positionForm = ref({
    id: null,
    name: '',
    code: '',
    organization: '',
    category: '',
    jobTitle: '',
    jobLevel: '',
    description: '',
    status: 'enabled'
})

// 表單驗證規則
const rules = {
    name: [{ required: true, message: '請輸入職位名稱', trigger: 'blur' }],
    code: [{ required: true, message: '請輸入職位編碼', trigger: 'blur' }],
    organization: [{ required: true, message: '請選擇所屬組織', trigger: 'change' }],
    category: [{ required: true, message: '請選擇職位類別', trigger: 'change' }],
    jobTitle: [{ required: true, message: '請選擇對應職務', trigger: 'change' }],
    jobLevel: [{ required: true, message: '請選擇職務級別', trigger: 'change' }]
}

// 下拉選項數據
const organizations = ref([
    { id: 1, name: '總公司' },
    { id: 2, name: '分公司A' },
    { id: 3, name: '分公司B' }
])

const categories = ref([
    {
        id: 1,
        name: '默認分類1',
        children: [
            { id: 3, name: '行政類' },
            { id: 4, name: '技術類' }
        ]
    },
    {
        id: 2,
        name: '默認分類2',
        children: [
            { id: 5, name: '管理類' },
            { id: 6, name: '銷售類' }
        ]
    }
])

const jobTitles = ref([
    { id: 1, name: '行政專員' },
    { id: 2, name: '工程師' },
    { id: 3, name: '經理' },
    { id: 4, name: '總監' }
])

const jobLevels = ref([
    { id: 'P1', name: 'P1' },
    { id: 'P2', name: 'P2' },
    { id: 'P3', name: 'P3' },
    { id: 'M1', name: 'M1' },
    { id: 'M2', name: 'M2' }
])

// 生命週期鉤子
onMounted(() => {
    fetchPositionData()
})

// 方法
const fetchPositionData = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        total.value = positionList.value.length
        loading.value = false
    }, 500)
}

const handleSearch = () => {
    currentPage.value = 1
    fetchPositionData()
}

const handleNodeClick = (data) => {
    console.log('點擊節點:', data)
    fetchPositionData()
}

const refreshTree = () => {
    ElMessage.success('職位類別樹已刷新')
}

const showAddDialog = () => {
    isEdit.value = false
    positionForm.value = {
        id: null,
        name: '',
        code: '',
        organization: '',
        category: '',
        jobTitle: '',
        jobLevel: '',
        description: '',
        status: 'enabled'
    }
    dialogVisible.value = true
}

const editPosition = (row) => {
    isEdit.value = true
    positionForm.value = { ...row }
    dialogVisible.value = true
}

const deletePosition = (row) => {
    ElMessageBox.confirm(`確定要刪除職位「${row.name}」嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        ElMessage.success('刪除成功')
        // 實際應該調用API刪除
        positionList.value = positionList.value.filter(item => item.id !== row.id)
        total.value = positionList.value.length
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const submitForm = () => {
    positionFormRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 更新職位
                const index = positionList.value.findIndex(item => item.id === positionForm.value.id)
                if (index !== -1) {
                    positionList.value[index] = { ...positionForm.value }
                }
                ElMessage.success('職位更新成功')
            } else {
                // 新增職位
                const newId = Math.max(...positionList.value.map(item => item.id)) + 1
                positionList.value.push({
                    ...positionForm.value,
                    id: newId
                })
                ElMessage.success('職位新增成功')
            }
            dialogVisible.value = false
            fetchPositionData()
        } else {
            return false
        }
    })
}

const importData = () => {
    ElMessage.info('導入功能')
}

const exportData = () => {
    ElMessage.success('開始導出數據')
}

const batchEnable = () => {
    ElMessage.success('批量啟用成功')
}

const batchDisable = () => {
    ElMessage.success('批量禁用成功')
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchPositionData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchPositionData()
}

</script>

<style scoped lang="less">
.position-management-container {
    padding: 20px;
    background-color: #fff;

    .top-action-bar {
        margin-bottom: 20px;
        padding: 16px 24px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        margin-top: 20px;

        .search-input-with-button {
            max-width: 500px;

            .el-input-group__append {
                background-color: var(--el-color-primary);
                color: white;
                border: none;

                &:hover {
                    opacity: 0.9;
                }
            }
        }

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }
    }

    .main-content-wrapper {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        padding: 16px;
        min-height: calc(100vh - 320px);
    }

    .position-category-card {
        border: 1px solid #ebeef5;
        border-radius: 8px;
        padding: 16px;
        height: 100%;
        background-color: #fff;

        .tree-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0 16px;

            .tree-title {
                font-size: 16px;
                font-weight: 600;
                color: #303133;
            }

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 4px;
            }
        }

        .custom-tree-node {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            padding-right: 8px;

            .node-count {
                color: #909399;
                font-size: 12px;
            }
        }

        .el-tree {
            :deep(.el-tree-node__content) {
                height: 36px;
            }
        }
    }

    .position-table-card {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;

        .no-border-table {

            :deep(.el-table__header),
            :deep(.el-table__body),
            :deep(.el-table__row),
            :deep(.el-table__cell) {
                border: none !important;
            }

            :deep(.el-table__header th) {
                background-color: #f4f8ff;
                font-weight: 600;
                padding: 20px;
            }

            :deep(.el-table__row):hover td {
                background-color: #f5f7fa !important;
            }
        }

        .pagination-wrapper {
            margin-top: 24px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>